<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class CategoryController extends Controller
{
    // 分类列表
	public function category_list()
	{
		$categorys = DB::table('category')->orderBy('cid','desc')->paginate(20);
		return view('admin/category_list',['categorys'=>$categorys]); 
	}
	
	// 添加列表
	public function category_add(Request $request)
	{
		if($request->isMethod('post')){
			$cname = $request->input('cname','','htmlspecialchars');
			if(empty($cname)) return redirect('/prompt')->with(['message'=>'分类名不能为空','url' =>'/admin/category_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 插入数据
			$res = DB::table('category')->insert(['cname'=>$cname]);
			if($res){
				return redirect('category_list');
			} else {
				return redirect('/prompt')->with(['message'=>'添加失败，请联系客服','url' =>'/admin/category_add', 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/category_add');
	}
	
	// 修改列表
	public function category_edit(Request $request,$cid)
	{
		if(!preg_match('/^[1-9]\d*$/',$cid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/category_list', 'jumpTime'=>3,'status'=>'error']);
		# 查询内容
		$category = DB::table('category')->where('cid',$cid)->select('cname','cid')->first();
		if($request->isMethod('post')){
			$cname = $request->input('cname','','htmlspecialchars');
			if(empty($cname)) return redirect('/prompt')->with(['message'=>'内容不能为空','url' =>'/admin/category_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 更新数据
			$res = DB::table('category')->where('cid',$cid)->update(['cname'=>$cname]);
			if($res){
				return redirect('category_list');
			} else {
				return redirect('/prompt')->with(['message'=>'更新失败，请联系客服','url' =>'/admin/category_edit/'.$cid, 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/category_edit',['category'=>$category]);
	}
	
	// 删除列表
	public function category_del(Request $request)
	{
		if($request->isMethod('post')){
			$cid = $request->input('cid');
			if(!preg_match('/^[1-9]\d*$/',$cid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/category_list', 'jumpTime'=>3,'status'=>'error']);
			
			# 删除数据
			$res = DB::table('category')->where('cid',$cid)->delete();
			if($res){
				json_return(200,'删除成功');
			} else {
				json_return(1000,'删除失败');
			}
		}
	}
	
	
	
}
